
import { ref, Ref, provide, useAttrs, onMounted } from 'vue';
import { compile, h } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { connectWebSocket, onWebSocket } from '/@/hooks/web/useWebSocket';
import { useUserStore } from '/@/store/modules/user';
import { useGlobSetting } from '/@/hooks/setting';
import RenderComponent from '../RenderComponent.vue'
import pubsub from 'pubsub-js'

const glob = useGlobSetting();

const userStore = useUserStore()

const { notification } = useMessage();

export const useMsgNotice = () => {
  const initNotice = async () => {
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    let url = `/push-ws-service/push/pc/${userStore.getUserInfo.id}`;
    connectWebSocket(url);
    onWebSocket(onWebSocketMessage);
    console.log("建立websocket链接成功,url: ", url)
  }

  const onWebSocketMessage = (res) => {
    console.log('收到服务端推送: ', res)
    if (res.code !== 1) {
      notification.error({
        message: '推送发生错误, 请联系提供商',
        description: res.message
      })
      return
    }
    // @ts-ignore

    // 站内消息推送(业务版) 不进行提示
    if (res.data.taskCode !== 'biz_site_push') {
      notification.open({
        key: `${res.data.bizType}_${res.data.varData.orderId}`,
        message: res.data.title,
        description: () => h(RenderComponent, {bizType: res.data.bizType, data: res.data}, {default: () => {}}),
        duration: 0,
      })
    } else {
      pubsub.publish('pushData', {bizType: res.data.bizType, data: res.data})
    }

  }

  return {
    initNotice
  }
}